package springboot.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import springboot.demo.annotation.NotProfile;
import springboot.demo.dao.UserMapper;

import java.util.Collections;

/**
 * 用户详情服务实现类
 * 实现Spring Security的UserDetailsService接口
 * 用于加载用户信息，支持Spring Security的认证机制
 */
@Service
@NotProfile("simple")
public class UserDetailsServiceImpl implements UserDetailsService {

    /**
     * 用户数据访问对象
     * 用于从数据库查询用户信息
     */
    private final UserMapper userMapper;

    /**
     * 构造函数注入UserMapper
     * @param userMapper 用户数据访问对象
     */
    public UserDetailsServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 根据用户名加载用户信息
     * 实现Spring Security的UserDetailsService接口方法
     *
     * 处理流程：
     * 1. 根据用户名查询用户信息
     * 2. 将用户信息转换为Spring Security的UserDetails对象
     * 3. 设置用户角色
     *
     * @param username 用户名（登录名）
     * @return 用户详情对象
     * @throws UsernameNotFoundException 当用户不存在时抛出此异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 使用MyBatis-Plus的条件构造器查询用户
        LambdaQueryWrapper<springboot.demo.bean.User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(springboot.demo.bean.User::getLoginname, username);
        springboot.demo.bean.User customUser = userMapper.selectOne(queryWrapper);
        
        if (customUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        
        // 创建Spring Security的UserDetails对象
        // 设置用户名、密码和角色
        return User.builder()
                .username(customUser.getLoginname())
                .password(customUser.getPassword())
                .authorities(Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + customUser.getType().toUpperCase())))
                .build();
    }
} 